<template>
    <div class="table-container" :class="{ 'virtual-mode': isVirtual }">
        <!-- 数据加载提示 -->
        <div v-if="isVirtual && isDataLoading" class="data-loading-info">
            <el-progress :percentage="loadingProgress" :format="(format: number) => `正在处理数据 ${format}%`"
                :stroke-width="15" />
        </div>

        <!-- 虚拟表格筛选区域 -->
        <div class="filter-row" v-if="isVirtual">
            <div v-for="column in visibleColumns" :key="column.prop" class="filter-item">
                <el-input v-model="filterValues[column.prop]" :placeholder="`筛选${column.label}`" clearable size="small"
                    @input="handleFilter">
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>

            </div>
            <el-button type="primary" link @click="clearAllFilters">
                <el-icon>
                    <Delete />
                </el-icon> 清空所有条件
            </el-button>
        </div>

        <!-- 表格 -->
        <div class="table-wrapper">
            <el-table ref="tableRef" v-loading="loading" :height="tableHeight" :max-height="tableHeight"
                :data="filteredData" style="width: 100%" @selection-change="handleSelectionChange"
                @row-click="handleRowClick" :highlight-current-row="true"
                :default-sort="{ prop: 'id', order: 'descending' }">
                <!-- 选择列 -->
                <el-table-column type="selection" width="55" v-if="!isVirtual" />

                <!-- Add expand column only for the first visible column, controlled by expandable prop -->
                <el-table-column v-if="expandable" type="expand" width="50">
                    <!-- 银行卡信息展示，如有需要可以做扩展 -->
                    <template #default="props">
                        <!-- 提现表格展开内容 -->
                        <div class="expanded-content" v-if="table_name === 'withdraw_basic'">
                            <div v-if="props.row.remark" 
                                 class="remark-box" 
                                 :class="{
                                    'success': props.row.state === '已审核',
                                    'danger': props.row.state === '驳回',
                                    'info': !props.row.state || (props.row.state !== '已审核' && props.row.state !== '驳回')
                                 }">
                                <div class="remark-title">
                                    <el-icon v-if="props.row.state === '已审核'" class="mr-5"><Check /></el-icon>
                                    <el-icon v-else-if="props.row.state === '驳回'" class="mr-5"><Close /></el-icon>
                                    <el-icon v-else class="mr-5"><InfoFilled /></el-icon>
                                    <span>{{ getStatusLabel(props.row.state) }}</span>
                                </div>
                                <div class="remark-content">
                                    {{ props.row.remark }}
                                </div>
                                <div v-if="props.row.auditor_time" class="remark-time">
                                    审核时间: {{ props.row.auditor_time }}
                                </div>
                            </div>
                            <el-empty v-else description="暂无备注信息" />
                        </div>
                        
                        <!-- 默认展开内容 - 通用数据展示 -->
                        <div class="expanded-content" v-else>
                            <div class="data-grid" v-if="Object.keys(props.row).length > 0">
                                <template v-for="column in visibleColumns" :key="column.prop">
                                    <div class="data-item" v-if="props.row[column.prop]">
                                        <p class="data-label">{{ column.label }}:</p>
                                        <template v-if="column.type === 'image'">
                                            <el-image 
                                                :src="props.row[column.prop]" 
                                                fit="cover"
                                                class="data-image"
                                                :preview-src-list="[props.row[column.prop]]">
                                            </el-image>
                                        </template>
                                        <p v-else class="data-value">{{ props.row[column.prop] }}</p>
                                    </div>
                                </template>
                            </div>
                            <el-empty v-else description="暂无详细信息" />
                        </div>
                    </template>
                </el-table-column>

                <!-- Regular columns without expand functionality -->
                <template v-for="column in visibleColumns" :key="column.prop">
                    <el-table-column :prop="column.prop" :label="column.label" :width="column.width"
                        :min-width="column.minWidth || 120" :show-overflow-tooltip="true" :sortable="true">
                        <template #default="{ row }">
                            <!-- 高亮显示筛选匹配的文本 -->
                            <template v-if="isVirtual && filterValues[column.prop] && column.type !== 'image'">
                                <span v-html="highlightText(row[column.prop], filterValues[column.prop])"></span>
                            </template>

                            <!-- 图片类型处理 -->
                            <template v-else-if="column.type === 'image'">
                                <el-image :src="row[column.prop] || DEFAULT_IMAGE"
                                    :style="column.imageStyle || defaultImageStyle"
                                    :preview-src-list="row[column.prop] ? [row[column.prop]] : []" fit="cover"
                                    :preview-teleported="true" :z-index="3000">
                                    <template #error>
                                        <div class="image-error">
                                            <el-icon>
                                                <Picture />
                                            </el-icon>
                                        </div>
                                    </template>
                                </el-image>
                            </template>

                            <!-- 按钮类型处理 -->
                            <template v-else-if="column.type === 'button' && !isDisabled(row, column)">
                                <el-button :type="column.buttonType || 'primary'" :size="column.buttonSize || 'small'"
                                    @click.stop="handleFunction(row, column)" :disabled="isDisabled(row, column)">
                                    {{ column.prop }}
                                </el-button>
                            </template>

                            <!-- 点击事件处理 -->
                            <template v-else-if="column.type === 'click'">
                                <span class="clickable-text" @click="handleClickColumn(row[column.prop], column.prop)">
                                    查看
                                </span>
                            </template>

                            <!-- 数字类型处理 -->
                            <template v-else-if="column.type === 'number'">
                                {{ row[column.prop] || 0 }}
                            </template>

                            <!-- 状态类型处理 -->
                            <template v-else-if="column.type === 'status'">
                                <el-tag :type="getTagType(row.state)">
                                    {{ row.state }}
                                </el-tag>
                            </template>

                            <!-- 默认内容显示 -->
                            <template v-else>
                                {{ row[column.prop] }}
                            </template>
                        </template>
                    </el-table-column>
                </template>
            </el-table>

        </div>

        <!-- 虚拟模式下的数据统计 -->
        <div class="filter-stats" v-if="isVirtual">
            <span>显示 {{ filteredData.length }} / {{ props.tableData.length }} 条记录</span>
            <span v-if="Object.values(filterValues).some(v => v)">
                (已筛选)
            </span>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { Picture, Search, Check, Close, InfoFilled } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'

import * as XLSX from 'xlsx'



interface TableColumn {
    prop: string
    label: string
    type?: 'text' | 'image' | 'button' | 'click'
    width?: string | number
    minWidth?: string | number
    showOverflow?: boolean
    imageStyle?: object
    show?: string
    buttonType?: 'primary' | 'success' | 'warning' | 'danger'
    buttonSize?: 'small' | 'default' | 'large'
    functionName?: string
    sortable?: boolean
    table_name?: string
}


interface Props {
    loading?: boolean
    tableData: any[]
    columns: TableColumn[]
    isVirtual?: boolean
    table_name?: string
    expandable?: boolean  // New prop to control expand functionality
    expandFields?: string[]  // Fields to display in expanded view
}

const props = withDefaults(defineProps<Props>(), {
    loading: false,
    isVirtual: false,
    table_name: '',
    expandable: false,  // Default to false - hide expand functionality
    expandFields: () => [] // Default empty array
})

// First, add the emit definition after props definition
const emit = defineEmits<{
    /**
     * 函数点击事件
     * @param params - 包含行数据和列数据的对象
     */
    'function-click': [params: { row: any; column: TableColumn }]
    /**
     * 当前页变化事件
     * @param value - 新的页码值
     */
    'current-change': [value: number]

    /**
     * 每页条数变化事件
     * @param value - 新的每页条数
     */
    'update:pageSize': [value: number]

    /**
     * 搜索事件
     * @param params - 搜索参数对象
     * @param params.keyword - 搜索关键词
     * @param params.page - 当前页码
     * @param params.pageSize - 每页条数
     */
    'search': [params: { keyword: string, page: number, pageSize: number }]

    /**
     * 重置事件
     */
    'reset': []

    /**
     * 新增事件
     */
    'add': []

    /**
     * 编辑事件
     * @param row - 要编辑的行数据
     */
    'edit': [row: any]

    /**
     * 删除事件
     * @param row - 要删除的行数据
     */
    'delete': [row: any]

    /**
     * 导出事件
     */
    'export': []

    /**
     * 打印事件
     */
    'print': []

    /**
     * 选择变化事件
     * @param selection - 当前选中的所有行数据
     */
    'selection-change': [selection: any[]]

    /**
     * 每页条数变化事件
     * @param size - 新的每页条数
     */
    'size-change': [size: number]

    /**
     * 行点击事件
     * @param row - 被点击的行数据
     */
    'row-click': [row: any]

    /**
     * 选择器值变化事件
     * @param value - 选择器的新值
     */
    'select-change': [value: string | number]

    /**
     * 虚拟模式切换事件
     */
    'virtual': []

    /**
     * 加载全部数据事件
     * @param params - 加载参数对象
     * @param params.limit - 限制加载的数据条数
     */
    'load-all-data': [params: { limit: number }]

    /**
     * 列点击事件
     * @param row - 被点击的行数据
     * @param column - 被点击的列数据
     */
    'column-click': [row: any, column: string]

    /**
     * 更新可扩展状态事件
     * @param value - 新的可扩展状态
     */
    'update:expandable': [value: boolean]
}>()

// 基础引用和变量
const tableRef = ref()
const virtualScrollRef = ref()
const selectedRows = ref<any[]>([])

// 虚拟滚动相关状态
const ROW_HEIGHT = 50  // 每行高度
const BUFFER_SIZE = 10 // 上下缓冲区行数
const visibleCount = ref(20) // 可见行数
const startIndex = ref(0)  // 起始索引
const endIndex = ref(0)    // 结束索引
const startOffset = ref(0) // 滚动偏移量
const isDataLoading = ref(false) // 数据加载状态
const loadingProgress = ref(0) // 加载进度

const getTagType = (state: string) => {
    //统计状态
    switch (state) {
        case '已筹满':
            return 'success'
        case '已付款':
            return 'success'
        case '正在众筹中':
            return 'warning'
        case '已取消':
            return 'danger'
        case '待付款':
            return 'warning'
        case '进行中':
            return 'success'
        case '已结束':
            return 'danger'
        default:
            return 'default'
        case '已审核':
            return 'success'
        case '提现审核中':
            return 'warning'
        case '驳回':
            return 'danger'

    }
}

//不同的表 不同的类型效果
const isDisabled = (row: any, column: TableColumn) => {
    console.log('visibleColumns数据', visibleColumns)
    if (column.type === 'button') {
        if (props.table_name === 'lovers') {
            return false
        }
        if (props.table_name === 'order_basic') {
            return !(row.state == '已付款' && row.pay_type == 'wxpay' && row.kind == 'order' && row.profit !== '已分润')
        }
        if (props.table_name === 'order_crowdfunding') {
            console.log('profit', row.profit)
            return !(row.profit !== '已分润' && row.state == '已筹满')
        }
        if (props.table_name === 'withdraw_basic') {
            return row.state !== '提现审核中'
        }
    }
    return false
}
// 每次滚动时重新计算可见区域
const recalculate = () => {
    if (!virtualScrollRef.value) return

    const scrollTop = virtualScrollRef.value.scrollTop || 0
    startIndex.value = Math.floor(scrollTop / ROW_HEIGHT)

    // 减去上方缓冲行
    startIndex.value = Math.max(0, startIndex.value - BUFFER_SIZE)

    // 计算可见行数
    visibleCount.value = Math.ceil(virtualScrollRef.value.clientHeight / ROW_HEIGHT) + 2 * BUFFER_SIZE

    // 计算结束索引
    endIndex.value = Math.min(startIndex.value + visibleCount.value, filteredData.value.length)

    // 计算偏移量
    startOffset.value = startIndex.value * ROW_HEIGHT
}

// 计算总高度
const totalHeight = computed(() => {
    return filteredData.value.length * ROW_HEIGHT
})

// 可见数据
const visibleData = computed(() => {
    if (!filteredData.value.length) return []
    return filteredData.value.slice(startIndex.value, endIndex.value)
})

// 筛选状态对象
const filterValues = reactive<Record<string, string>>({})
const globalSearchText = ref('')
const originalDataCount = ref(0)
const hasFilter = computed(() =>
    Object.values(filterValues).some(v => !!v) || !!globalSearchText.value
)

// 排序状态
const sortInfo = reactive({
    prop: '',
    order: 'descending'
})

// 排序方法
const sortByColumn = (prop: string) => {
    if (sortInfo.prop === prop) {
        sortInfo.order = sortInfo.order === 'ascending' ? 'descending' : 'ascending'
    } else {
        sortInfo.prop = prop
        sortInfo.order = 'ascending'
    }

    // 应用排序 (在WebWorker中进行)
    applyFiltersAndSort()
}

// 防抖处理筛选
const debounceFilter = debounce(() => {
    applyFiltersAndSort()
}, 300)

// 防抖处理全局搜索
const debounceGlobalSearch = debounce(() => {
    applyFiltersAndSort()
}, 300)

// 计算可见列
const visibleColumns = computed(() => {
    const columns = props.columns || [];
    console.log("Computing visible columns from:", columns.length, "columns");
    return columns.filter(col => col.show !== false);
})

// 获取列宽
const getColumnWidth = (column: any) => {
    return parseInt(column.width) || 150
}

// 处理图片加载错误
const handleImageError = (e: Event) => {
    const target = e.target as HTMLImageElement
    target.src = DEFAULT_IMAGE
}

// 用于唯一标识行的key
const getRowKey = (row: any, index: number) => {
    return row.id || row.idpk || `row-${index}`
}

// 为了防止重复创建，使用 ref 存储 worker
const dataWorker = ref<Worker | null>(null)

// 初始化 WebWorker
const initDataWorker = () => {
    // 如果浏览器支持 WebWorker
    if (window.Worker) {
        const workerCode = `
            let originalData = [];
            let filteredData = [];
            
            // 接收主线程消息
            self.onmessage = function(e) {
                const { type, data } = e.data;
                
                if (type === 'init') {
                    // 初始化数据
                    originalData = data;
                    filteredData = [...originalData];
                    self.postMessage({ type: 'initialized', count: originalData.length });
                }
                else if (type === 'filter') {
                    // 应用筛选和排序
                    const { filters, globalSearch, sortProp, sortOrder } = data;
                    
                    // 先通知开始处理
                    self.postMessage({ type: 'processingStart' });
                    
                    // 分批处理大数据集，每处理5000条发送一次进度
                    const batchSize = 5000;
                    let progress = 0;
                    
                    // 先进行筛选
                    filteredData = originalData.filter((row, index) => {
                        // 每处理一批数据发送进度
                        if (index % batchSize === 0) {
                            progress = Math.floor((index / originalData.length) * 50);
                            self.postMessage({ type: 'progress', progress });
                        }
                        
                        // 全局搜索
                        if (globalSearch) {
                            const matchesGlobal = Object.keys(row).some(key => {
                                const value = String(row[key] || '').toLowerCase();
                                return value.includes(globalSearch.toLowerCase());
                            });
                            if (!matchesGlobal) return false;
                        }
                        
                        // 字段筛选
                        for (const [prop, value] of Object.entries(filters)) {
                            if (!value) continue;
                            
                            const cellValue = String(row[prop] || '').toLowerCase();
                            const filterValue = value.toLowerCase();
                            
                            if (!cellValue.includes(filterValue)) {
                                return false;
                            }
                        }
                        
                        return true;
                    });
                    
                    // 进度提升到70%
                    self.postMessage({ type: 'progress', progress: 70 });
                    
                    // 然后进行排序
                    if (sortProp) {
                        filteredData.sort((a, b) => {
                            const valueA = a[sortProp];
                            const valueB = b[sortProp];
                            
                            // 处理不同类型的值
                            if (typeof valueA === 'number' && typeof valueB === 'number') {
                                return sortOrder === 'ascending' ? valueA - valueB : valueB - valueA;
                            } else {
                                const strA = String(valueA || '').toLowerCase();
                                const strB = String(valueB || '').toLowerCase();
                                return sortOrder === 'ascending' ? 
                                    strA.localeCompare(strB) : 
                                    strB.localeCompare(strA);
                            }
                        });
                    }
                    
                    // 通知处理完成
                    self.postMessage({ 
                        type: 'filtered', 
                        data: filteredData,
                        count: filteredData.length
                    });
                }
            };
        `;

        // 创建 Blob URL
        const blob = new Blob([workerCode], { type: 'application/javascript' });
        const workerUrl = URL.createObjectURL(blob);

        // 创建 Worker
        dataWorker.value = new Worker(workerUrl);

        // 监听 Worker 消息
        dataWorker.value.onmessage = (e) => {
            const { type, data, count, progress } = e.data;

            if (type === 'initialized') {
                originalDataCount.value = count;
                isDataLoading.value = false;
            }
            else if (type === 'processingStart') {
                isDataLoading.value = true;
                loadingProgress.value = 0;
            }
            else if (type === 'progress') {
                loadingProgress.value = progress;
            }
            else if (type === 'filtered') {
                // 将过滤后的数据设置到本地
                filteredDataRef.value = data;
                isDataLoading.value = false;
                loadingProgress.value = 100;

                // 重置虚拟滚动状态
                startIndex.value = 0;
                startOffset.value = 0;

                if (virtualScrollRef.value) {
                    virtualScrollRef.value.scrollTop = 0;
                }

                // 重新计算可见区域
                nextTick(() => {
                    recalculate();
                });
            }
        };
    }
};

// 引用到过滤后的数据
const filteredDataRef = ref<any[]>([]);

// 计算属性：过滤后的数据
const filteredData = computed(() => {
    console.log("Computing filteredData. Raw data:", props.tableData?.length || 0, "items");
    
    if (!props.isVirtual || Object.values(filterValues).every(v => !v)) {
        return props.tableData || [];
    }

    return props.tableData.filter(row => {
        // 检查每个过滤条件
        return Object.entries(filterValues).every(([prop, value]) => {
            if (!value) return true; // 如果没有过滤值，则通过

            // 防止undefined或null值导致错误
            const cellValue = row[prop] == null ? '' : String(row[prop]).toLowerCase();
            const filterValue = value.toLowerCase();

            // 返回是否匹配
            return cellValue.includes(filterValue);
        });
    });
});

// 应用筛选和排序 (使用 WebWorker)
const applyFiltersAndSort = () => {
    if (!dataWorker.value || !props.isVirtual) return;

    dataWorker.value.postMessage({
        type: 'filter',
        data: {
            filters: filterValues,
            globalSearch: globalSearchText.value,
            sortProp: sortInfo.prop,
            sortOrder: sortInfo.order
        }
    });
};

// 监听表格数据变化
watch(() => props.tableData, (newData) => {
    if (props.isVirtual && dataWorker.value && newData.length > 0) {
        // 数据加载中状态
        isDataLoading.value = true;
        loadingProgress.value = 0;

        // 初始化 Worker 数据
        dataWorker.value.postMessage({
            type: 'init',
            data: newData
        });

        // 初始化 filteredDataRef
        filteredDataRef.value = newData;
        originalDataCount.value = newData.length;
    }
}, { immediate: true });

// 监听虚拟模式变化
watch(() => props.isVirtual, (newIsVirtual) => {
    if (newIsVirtual) {
        // 只记录数据量，不试图克隆整个数据集
        console.log("虚拟表格模式已激活 - 数据量:", props.tableData.length);

        // 延迟执行可能的DOM操作
        nextTick(() => {
            // 确保表格容器样式正确
            const container = document.querySelector('.table-container');
            if (container) {
                container.classList.add('virtual-mode');
            }
        });
    } else {
        nextTick(() => {
            const container = document.querySelector('.table-container');
            if (container) {
                container.classList.remove('virtual-mode');
            }
        });
    }
}, { immediate: true });

// 清理筛选值 - 当数据或模式变化时
watch([() => props.tableData, () => props.isVirtual], () => {
    // 仅在模式或数据变化时重置筛选值
    if (!props.isVirtual) {
        Object.keys(filterValues).forEach(key => {
            filterValues[key] = '';
        });
    }
});

// 高亮显示匹配文本
const highlightText = (text: string | number, search: string) => {
    if (!text || !search) return text;

    const stringText = String(text);
    const searchLower = search.toLowerCase();
    const textLower = stringText.toLowerCase();

    // 如果没有匹配，直接返回原文本
    if (!textLower.includes(searchLower)) return stringText;

    // 查找匹配位置
    const index = textLower.indexOf(searchLower);

    // 分割文本并高亮
    const before = stringText.substring(0, index);
    const matched = stringText.substring(index, index + search.length);
    const after = stringText.substring(index + search.length);

    return `${before}<span class="highlight-match">${matched}</span>${after}`;
};

// 组件卸载时清理 Worker
onBeforeUnmount(() => {
    if (dataWorker.value) {
        dataWorker.value.terminate();
        dataWorker.value = null;
    }
});

// 虚拟滚动事件处理
const handleVirtualScroll = debounce(() => {
    recalculate();
}, 10);

// 组件挂载时设置
onMounted(() => {
    // Initialize columns for virtual scrolling
    if (props.isVirtual) {
        initVirtualColumns();

        // Set up virtual scrolling
        if (virtualScrollRef.value) {
            virtualScrollRef.value.addEventListener('scroll', handleVirtualScroll);
        }

        // Initialize data worker
        initDataWorker();
    }

    // Apply default sort
    sortInfo.prop = defaultSort.prop;
    sortInfo.order = defaultSort.order;

    // 初始计算可见区域
    nextTick(() => {
        if (props.isVirtual) {
            recalculate();
        }
    });

    // 添加调整大小的监听器
    window.addEventListener('resize', handleResize);

    // 设置初始容器样式
    const container = document.querySelector('.table-container');
    if (container && props.isVirtual) {
        container.classList.add('virtual-mode');
    }
});

// 处理窗口大小变化
const handleResize = debounce(() => {
    if (props.isVirtual) {
        recalculate();
    }
}, 100);
const handleRowClick = (row: any) => {
    console.log(row);
    emit('row-click', row);
}
// 添加表格高度计算
const tableHeight = computed(() => {
    // 如果是虚拟模式，减去筛选区域的高度
    return props.isVirtual ? 530 : 600; // 调整这些数值以适应您的布局
});

const DEFAULT_IMAGE = 'https://element-plus.org/images/element-plus-logo.svg';

const defaultImageStyle = {
    width: '40px',
    height: '40px',
    objectFit: 'cover' as const,
    borderRadius: '4px'
};

// 修改导出函数
const handleExport = () => {
    try {
        const dataToExport = selectedRows.value.length > 0
            ? selectedRows.value
            : filteredData.value;

        // 使用简单的转换和导出
        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.json_to_sheet(dataToExport);
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

        // 写入并下载文件
        XLSX.writeFile(workbook, 'table-export.xlsx');
    } catch (error) {
        console.error('导出失败:', error);
    }
};

// 替换掉复杂的导出函数实现，移除enhancedExportToExcel

// Handle print functionality
const handlePrint = () => {
    if (selectedRows.value.length === 0) return;

    // Create a printable version of the selected data
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    // Generate HTML for printing
    let html = '<html><head><title>Print</title>';
    html += '<style>table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }</style>';
    html += '</head><body>';
    html += '<h2>Selected Data</h2>';
    html += '<table>';

    // Add headers
    html += '<tr>';
    props.columns.forEach(col => {
        if (col.show === '1') {
            html += `<th>${col.label}</th>`;
        }
    });
    html += '</tr>';

    // Add rows
    selectedRows.value.forEach(row => {
        html += '<tr>';
        props.columns.forEach(col => {
            if (col.show === '1') {
                html += `<td>${row[col.prop] || ''}</td>`;
            }
        });
        html += '</tr>';
    });

    html += '</table></body></html>';

    // Write to the print window and print
    printWindow.document.write(html);
    printWindow.document.close();
    printWindow.onload = () => {
        printWindow.print();
        printWindow.close();
    };
};

// 暴露方法给父组件
defineExpose({
    //暴露tabaleref内置方法 详情见 element-plus官网
    setCurrentRow: (row: any) => {
        if (tableRef.value) {
            tableRef.value.setCurrentRow(row);
        }
    },
    clearSelection: () => {
        if (tableRef.value) {
            tableRef.value.clearSelection();
        }
    },
    //暴露表格展开后
    setExpandable: (value: boolean) => {
        // This won't work directly since props are immutable
        // This is for documentation - implement through events
        console.log('Expandable state requested change to:', value);
        emit('update:expandable', value);
    },
    selectedRows,
    handleExport,   // 暴露导出函数
    handlePrint     // 暴露打印函数
});

// 默认排序设置
const defaultSort = {
    prop: 'id',
    order: 'descending'
};

// 清除所有筛选条件
const clearAllFilters = () => {
    Object.keys(filterValues).forEach(key => {
        filterValues[key] = '';
    });
    // 手动触发筛选更新
    handleFilter();
};

// 监听窗口大小变化
onMounted(() => {
    window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
});

// Add missing methods

// Handle filter input
const handleFilter = () => {
    applyFiltersAndSort();
}

// Handle selection change
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection;
    emit('selection-change', selection);
}

// Handle function button click
const handleFunction = (row: any, column: TableColumn) => {
    emit('function-click', { row, column });
}

// Now handle the unused variables - we'll either use them or remove as needed

// These can be removed as they're not used
// const tableWrapperRef = ref() - removing below
// const currentRow = ref<any>(null) - removing below

// For the computed values, either use them or remove
// Implementing visibleData usage in the template would require major rework
// so we'll keep them but use them meaningfully where possible

// Add watch to use hasFilter
watch(() => hasFilter.value, (newHasFilter) => {
    //console.log('Filter status changed:', newHasFilter);
});

// Add watch to use totalHeight
watch(() => totalHeight.value, (newHeight) => {
    if (virtualScrollRef.value) {
        virtualScrollRef.value.style.height = `${newHeight}px`;
    }
});

// Use visibleData in a meaningful way
watch(() => visibleData.value, (newVisibleData) => {
    if (props.isVirtual) {
        console.log(`Showing ${newVisibleData.length} rows in virtual view`);
    }
});

// Use getColumnWidth, sortByColumn, etc. in appropriate places
const initVirtualColumns = () => {
    props.columns.forEach(column => {
        const width = getColumnWidth(column);
        console.log(`Column ${column.prop} width: ${width}px`);
    });
};

// Use debounceFilter and debounceGlobalSearch
const triggerFilterUpdate = () => {
    debounceFilter();
};

const triggerGlobalSearch = (text: string) => {
    globalSearchText.value = text;
    debounceGlobalSearch();
};

// Use handleImageError
watch(() => props.tableData, () => {
    // Add image error handler to any images in the table
    nextTick(() => {
        const images = document.querySelectorAll('.table-container .el-image img');
        images.forEach(img => {
            img.addEventListener('error', handleImageError);
        });
    });
});

// 处理点击事件
const handleClickColumn = (row: any, column: string) => {
    emit('column-click', row, column)
}

// Add a function to get status label text
const getStatusLabel = (state: string) => {
    switch (state) {
        case '已审核':
            return '审核通过';
        case '驳回':
            return '审核驳回';
        case '提现审核中':
            return '待审核';
        default:
            return state || '未知状态';
    }
}

// Function to get friendly field labels
const getFieldLabel = (field: string) => {
    const fieldLabels: Record<string, string> = {
        'pic1': '活动封面',
        'pic2': '图片2',
        'pic3': '图片3',
        'pic4': '图片4',
        'detailpic': '详情图片'
    };
    return fieldLabels[field] || field;
};

// Check if row has any image fields
const hasImageField = (row: any) => {
    const imageFields = ['pic1', 'pic2', 'pic3', 'pic4', 'detailpic'];
    return imageFields.some(field => row[field]);
}

// Check if row has any additional images
const hasAdditionalImages = (row: any) => {
    // Check for carousel images
    if (row.pic2 || row.pic3 || row.pic4 || row.detailpic) {
        return true;
    }
    
    // Check for detail images (detailpic1 through detailpic20)
    for (let i = 1; i <= 20; i++) {
        if (row[`detailpic${i}`]) {
            return true;
        }
    }
    
    return false;
}
</script>

<style lang="scss" scoped>
.table-container {
    display: flex;
    flex-direction: column;
    height: 100%;

    .filter-row {
        flex-shrink: 0; // 防止筛选区域被压缩
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 10px;
        background-color: #f5f7fa;
        padding: 12px;
        border-radius: 4px;

        .filter-item {
            width: 200px;
        }
    }

    .table-wrapper {
        flex: 1;
        min-height: 0; // 这很重要，确保flex子项不会溢出
        position: relative;
        overflow: hidden;

        // 确保表格填充整个容器
        :deep(.el-table) {
            height: 100%;
        }

        // 修复滚动条被遮挡的问题
        :deep(.el-table__body-wrapper) {
            overflow-x: auto !important;
            overflow-y: auto !important;
        }
    }

    &.virtual-mode {
        height: calc(100vh - 230px); // 调整为适合您页面的高度
    }

    .filter-stats {
        flex-shrink: 0;
        padding: 8px 0;
        text-align: right;
        color: var(--el-text-color-secondary);
        font-size: 13px;
    }

    // 虚拟模式特殊样式
    &.virtual-mode {
        .table-wrapper {
            border: 1px solid #EBEEF5;
            border-radius: 4px;
        }
    }

    // 高亮显示样式
    :deep(.highlight-match) {
        background-color: #ffff90;
        font-weight: bold;
        padding: 0 2px;
        border-radius: 2px;
    }

    .image-error {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f7fa;
        border-radius: 4px;
        color: #909399;
    }

    :deep(.el-table__row) {
        cursor: pointer;
    }

    :deep(.current-row) {
        background-color: var(--el-table-row-hover-bg-color);
    }

    // Add styles for the expanded content
    .expanded-content {
        padding: 16px;
        
        .remark-box {
            padding: 12px 16px;
            border-radius: 4px;
            border-left: 4px solid #909399;
            background-color: #f4f4f5;
            margin-bottom: 10px;
            
            &.success {
                border-left-color: #67c23a;
                background-color: #f0f9eb;
            }
            
            &.danger {
                border-left-color: #f56c6c;
                background-color: #fef0f0;
            }
            
            &.info {
                border-left-color: #909399;
                background-color: #f4f4f5;
            }
            
            .remark-title {
                font-weight: 500;
                font-size: 14px;
                margin-bottom: 8px;
                display: flex;
                align-items: center;
                
                .mr-5 {
                    margin-right: 5px;
                }
            }
            
            .remark-content {
                font-size: 14px;
                line-height: 1.5;
                color: #606266;
                white-space: pre-wrap;
                word-break: break-word;
            }
            
            .remark-time {
                margin-top: 10px;
                font-size: 12px;
                color: #909399;
                text-align: right;
            }
        }
        
        .activity-images {
            margin-top: 20px;
            
            h4 {
                font-size: 16px;
                margin-bottom: 12px;
                color: #606266;
            }
            
            .image-grid {
                display: flex;
                flex-wrap: wrap;
                gap: 15px;
                
                .image-item {
                    width: 120px;
                    
                    .el-image {
                        width: 120px;
                        height: 120px;
                        border-radius: 4px;
                        overflow: hidden;
                    }
                    
                    .image-caption {
                        text-align: center;
                        padding: 5px;
                        font-size: 12px;
                        color: #606266;
                    }
                }
            }
        }

        .profile-card {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
            padding: 0;
            overflow: hidden;
            
            .profile-header {
                display: flex;
                padding: 16px;
                background-color: #f9f9f9;
                border-bottom: 1px solid #eaeaea;
                
                .profile-image {
                    width: 80px;
                    height: 80px;
                    margin-right: 16px;
                    border-radius: 4px;
                    overflow: hidden;
                    
                    .el-image {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }
                }
                
                .profile-info {
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    
                    h3 {
                        margin: 0 0 8px 0;
                        font-size: 18px;
                        font-weight: 600;
                        color: #303133;
                    }
                    
                    .profile-meta {
                        display: flex;
                        align-items: center;
                        flex-wrap: wrap;
                        gap: 12px;
                        
                        .meta-item {
                            font-size: 14px;
                            color: #606266;
                            
                            strong {
                                font-weight: 500;
                            }
                        }
                    }
                }
            }
            
            .profile-body {
                padding: 16px;
                
                .info-section {
                    margin-bottom: 20px;
                    
                    .info-row {
                        margin-bottom: 12px;
                        
                        strong {
                            display: block;
                            font-weight: 500;
                            color: #606266;
                            margin-bottom: 4px;
                        }
                        
                        .info-content {
                            font-size: 14px;
                            color: #303133;
                            line-height: 1.5;
                            padding: 8px 12px;
                            background-color: #f9f9f9;
                            border-radius: 4px;
                            word-break: break-word;
                        }
                    }
                }
                
                .image-gallery {
                    .gallery-title {
                        font-weight: 500;
                        color: #606266;
                        margin-bottom: 12px;
                    }
                    
                    .gallery-images {
                        display: flex;
                        flex-wrap: wrap;
                        gap: 10px;
                        
                        .gallery-image {
                            width: 120px;
                            height: 140px;
                            border-radius: 4px;
                            overflow: hidden;
                            position: relative;
                            
                            .el-image {
                                width: 100%;
                                height: 120px;
                                object-fit: cover;
                            }
                            
                            .image-label {
                                font-size: 12px;
                                color: #606266;
                                text-align: center;
                                padding: 2px 0;
                                background-color: #f5f7fa;
                            }
                        }
                    }
                }
            }
        }
    }
}

.clickable-text {
    color: #409EFF;
    cursor: pointer;
}

.clickable-text:hover {
    text-decoration: underline;
}

/* Add data-grid styling */
.data-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    .data-item {
        border-bottom: 1px solid #ebeef5;
        padding-bottom: 12px;
        
        .data-label {
            font-size: 14px;
            color: #606266;
            font-weight: 500;
            margin: 0 0 8px 0;
        }
        
        .data-value {
            font-size: 14px;
            color: #303133;
            margin: 0;
        }
        
        .data-image {
            width: 100px;
            height: 100px;
            border-radius: 4px;
            object-fit: cover;
        }
    }
}
</style>
